const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 获取收藏列表
router.get('/', async (req, res) => {
  try {
    const user_id = req.user.id;
    const [favorites] = await db.promise().query(`
      SELECT f.*, p.*
      FROM product_favorites f
      LEFT JOIN products p ON f.product_id = p.id
      WHERE f.user_id = ?
      ORDER BY f.created_at DESC
    `, [user_id]);

    res.json({
      success: true,
      data: favorites
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 添加收藏
router.post('/', async (req, res) => {
  try {
    const { product_id } = req.body;
    const user_id = req.user.id;

    // 检查是否已收藏
    const [existing] = await db.promise().query(
      'SELECT id FROM product_favorites WHERE user_id = ? AND product_id = ?',
      [user_id, product_id]
    );

    if (existing.length > 0) {
      return res.status(400).json({
        success: false,
        error: '已经收藏过该商品',
        code: 400
      });
    }

    await db.promise().query(
      'INSERT INTO product_favorites (user_id, product_id) VALUES (?, ?)',
      [user_id, product_id]
    );

    res.json({
      success: true,
      message: '收藏成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 取消收藏
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    await db.promise().query(
      'DELETE FROM product_favorites WHERE id = ? AND user_id = ?',
      [id, user_id]
    );

    res.json({
      success: true,
      message: '取消收藏成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

module.exports = router; 